package com.party.web.web.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.city.Area;
import com.party.core.model.city.City;
import com.party.core.model.commune.*;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.*;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.system.TargetType;
import com.party.core.service.city.IAreaService;
import com.party.core.service.city.ICityService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.commune.ICMemberRecommendService;
import com.party.core.service.commune.impl.CIntegralBizService;
import com.party.core.service.commune.impl.CIntegralItemService;
import com.party.core.service.commune.impl.CUserIntegralService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.crowdfund.ITargetTemplateService;
import com.party.core.service.member.*;
import com.party.core.service.member.biz.PartnerMemberToBizService;
import com.party.core.service.system.ISysRoleService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.member.CIntegralBizToService;
import com.party.web.biz.member.MemberMgmtNotifyService;
import com.party.web.biz.member.MemberMgmtService;
import com.party.web.biz.system.member.MemberBizService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.annotation.UserOperate;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.system.SelectMemberInput;
import com.party.web.web.dto.output.member.ProjectForMembermUserOutput;
import com.party.web.web.dto.output.member.ProjectForMembermgmtOutput;
import com.party.web.web.security.CurrentUser;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 会员管理
 * @Author: yangshoukun
 * @Date: 2018/2/22 10:56
 */
@Controller
@RequestMapping(value = "member/membermgmt")
public class MemberMgmtController {

    @Autowired
    private MemberMgmtService memberMgmtService;

    @Autowired
    private MemberMgmtNotifyService memberMgmtNotifyService;

    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private ICMemberInfoService memberInfoService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private PartnerMemberToBizService partnerMemberToBizService;
    @Autowired
    private ICMemberRecommendService memberRecommendService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ITargetTemplateService targetTemplateService;
    @Autowired
    private IPackageCountService packageCountService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private CIntegralBizService integralBizService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @Autowired
    private CIntegralBizToService cIntegralBizToService;

    @Autowired
    private CIntegralItemService cIntegralItemService;
    @Autowired
    private CUserIntegralService userIntegralService;

    @Autowired
    private ICIntegralTypeService integralTypeService;

    @Autowired
    private MemberGroupBizService memberGroupBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "list")
    public ModelAndView list(MemberMgmtQuery input, Page page) {

        CurrentUser member = RealmUtils.getNewCurrentUser();

        ModelAndView mv = new ModelAndView("member/membermgmt");
        page.setLimit(20);
        if (null == input.getType()) {
            input.setType(0);
        }
        List<MemberGroup> memberGroupList = new ArrayList<>();
        if (!member.isChild()) {
            memberGroupList = memberGroupService.getChildWithMyAndName(member.getId());
            if (StringUtils.isEmpty(input.getMemberGroupId())) {
                input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
            }
        }
        if (!Constant.MEMBER_XZGSADMIN.equals(member.getType())) {
            List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
            input.setOrgIds(orgIds);
        } else {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(member.getId(), member.getPartnerId());
        }
        mv.addObject("memberGroupList", memberGroupList);
        List<Map<String, Object>> list = memberMgmtService.webList(input, "", page);
        for (Map<String, Object> mmp : list) {
            //获取保存在主分社的二维码路径
            String memberId = mmp.get("memberId").toString();
            String partnerId = mmp.get("partnerId").toString();
            String pmId = mmp.get("pmId").toString();
            PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, partnerId);
            if (mainOrg != null) {
                pmId = mainOrg.getId();
                partnerId = mainOrg.getPartnerId();
            }
            String filePath = fileBizService.getUploadCIPath(partnerId, "integral");
            String url = cosBizService.getPreviewPictureUrl(filePath + pmId);
            mmp.put("qrCodeUrl", url);
            mmp.put("userSerial",mainOrg.getUserSerial());
        }

        //是否拥有行知公社权限
        boolean isCommune = cIntegralBizToService.isXZGSJurisdiction(member.getId());
        mv.addObject("isCommune", isCommune);
        mv.addObject("isXzgsAdmin", member.isXzgsAdmin());
        Map<Integer, String> types = MemberMgmtType.convertMap();
        mv.addObject("types", types);

        mv.addObject("list", list);
        mv.addObject("input", input);
        mv.addObject("page", page);
        mv.addObject("partentId", member.getId());
        mv.addObject("isChild", member.isChild());
        return mv;


    }

    /**
     * @param input
     * @param response
     * @Description: 会员管理表格数据导出
     * @Author: huangwuming
     * @Date: 2018/2/27 10:56
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_LISTEXPORT)
    @ResponseBody
    @RequestMapping(value = "listExport")
    public AjaxResult listExport(MemberMgmtQuery input, HttpServletResponse response) {
        String headName = "";
        if (input.getType() == 0) {
            headName = "会员管理";
        }
        if (input.getType() == 1) {
            headName = "用户管理";
        }
        String fileName = headName + DateUtils.todayDate() + ".xlsx";

        CurrentUser member = RealmUtils.getNewCurrentUser();
        //String partnerId = member.getId();


        if (!member.isChild()) {
            if (StringUtils.isEmpty(input.getMemberGroupId())) {
                input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
            }
        }
        if (!Constant.MEMBER_XZGSADMIN.equals(member.getType())) {
            List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
            input.setOrgIds(orgIds);
        }

        List<Map<String, Object>> list = memberMgmtService.webList(input, "", null);
        try {
            ExportExcel exportExcel = null;
            //设置会员导出的excel表头单元格
            if (input.getType() == 0) {
                exportExcel = new ExportExcel(fileName, ProjectForMembermgmtOutput.class);
            }
            //设置用户导出的excel表头单元格
            if (input.getType() == 1) {
                exportExcel = new ExportExcel(fileName, ProjectForMembermUserOutput.class);
            }
            exportExcel = memberMgmtService.setDataList(list, exportExcel, input, null);
            String allPath = memberMgmtService.getExcelPath(fileName, "membermgmt", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出会员异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    @RequestMapping(value = "form")
    public ModelAndView form(String pmId, String pageNo) {

        ModelAndView mv = new ModelAndView("member/cmemberForm");
        Member member = null;
        CMemberInfo memberInfo = null;
        Member tjMember = null;
        String city = null;
        String arParent = null;

        String industryId = null;
        String idParent = null;
        if (StringUtils.isNotEmpty(pmId)) {
            //用户
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            member = memberService.get(partnerMember.getMemberId());
            //用户详细信息
            memberInfo = memberInfoService.getByMemberId(partnerMember.getMemberId());
            //推荐人
            PartnerMember mainOrg = partnerMemberService.getMainOrg(partnerMember.getMemberId(), partnerMember.getPartnerId());
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setuId(mainOrg.getId());
            List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
            if (list.size() > 0) {
                CMemberRecommend cMemberRecommend1 = list.get(0);
                PartnerMember tj_partnerMember = partnerMemberService.get(cMemberRecommend1.getParentId());
                tjMember = memberService.get(tj_partnerMember.getMemberId());
            }
            //地区
            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                if (area != null) {
                    city = area.getId();
                    arParent = area.getParentId();
                }
            }
            //行业
            if (StringUtils.isNotEmpty(member.getIndustry())) {
                Industry industry = industryService.get(member.getIndustry());
                if (industry != null) {
                    industryId = industry.getId();
                    idParent = industry.getParentId();
                }
            }
            if (memberInfo == null) {
                memberInfo = new CMemberInfo();
            }
            //用户编号
            memberInfo.setUserSerial(mainOrg.getUserSerial());
        }

        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);

        City city1 = new City();
        city1.setIsOpen(1);
        mv.addObject("citys", cityService.list(city1));


        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);

        mv.addObject("city", city);
        mv.addObject("arParent", arParent);

        mv.addObject("industryId", industryId);
        mv.addObject("idParent", idParent);

        mv.addObject("member", member);
        mv.addObject("pmId", pmId);
        mv.addObject("tjMember", tjMember);
        mv.addObject("memberInfo", memberInfo);
        mv.addObject("pageNo",pageNo);
        return mv;
    }

    /**
     * @Description: 编辑用户
     * @Param: [input, request]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_UPDATE)
    @ResponseBody
    @RequestMapping(value = "saveOrUpdate")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(CMemberInfo input) {

        if (StringUtils.isEmpty(input.getLogo())) {
            return AjaxResult.error("用户头像为空");
        }
        if (StringUtils.isEmpty(input.getRealname())) {
            return AjaxResult.error("用户姓名为空");
        }
        if (StringUtils.isEmpty(input.getMobile())) {
            return AjaxResult.error("用户手机号为空");
        }
        try {
/*            if (StringUtils.isNotEmpty(input.getTjMemberId())) {
                if (input.getTjMemberId().equals(input.getId())) {
                    return AjaxResult.error("推荐人不能是当前添加的用户");
                }

                String partnerId = RealmUtils.getCurrentUser().getId();
                if (StringUtils.isNotEmpty(input.getPmId())) {
                    PartnerMember partnerMember = partnerMemberService.get(input.getPmId());
                    partnerId = partnerMember.getPartnerId();
                }
                PartnerMember tj_ppartnerMember = partnerMemberService.
                        findByPartnerAndMember(partnerId, input.getTjMemberId());//获取推荐人的pmId

                CMemberRecommend cMemberRecommend = new CMemberRecommend();
                cMemberRecommend.setParentId(input.getPmId());
                cMemberRecommend.setuId(tj_ppartnerMember.getId());

                List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend); // 判断是否存在 相互推荐
                if (list.size() > 0) {
                    return AjaxResult.error("不能相互推荐");
                }
            }*/

            if (StringUtils.isNotEmpty(input.getUserSerial())) {
                String userSerial = input.getUserSerial().trim();
                PartnerMember queryPartnerMember = new PartnerMember();
                queryPartnerMember.setUserSerial(userSerial);
                List<PartnerMember> list = partnerMemberService.list(queryPartnerMember);
                if (list.size() > 0) {
                    PartnerMember pmOrg = list.get(0);
                    if (!pmOrg.getMemberId().equals(input.getId())) {
                        return AjaxResult.error("已存在相同的编号");
                    }
                }
                input.setUserSerial(userSerial);
            }

            memberBizService.saveOrUpdateCmember(input);
        } catch (Exception e) {
            logger.error("编辑用户异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑用户异常", e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * @Description: 获取用户信息
     * @Param: [memberId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @ResponseBody
    @RequestMapping(value = "getcMemberInfo")
    public AjaxResult getcMemberInfo(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("参数为空");
        }
        try {
            Map<String, Object> mmp = Maps.newHashMap();

            String arParent = "";

            Member member = memberService.get(memberId);
            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                arParent = area.getParentId();
            }
            CMemberInfo cMemberInfo = memberInfoService.getByMemberId(memberId);
            PartnerMember partnerMember = partnerMemberService.getMainOrg(memberId,memberGroupBizService.getXzgsMemberId());
            if (cMemberInfo == null) {
                cMemberInfo = new CMemberInfo();
            }
            if (partnerMember != null) {
                cMemberInfo.setUserSerial(partnerMember.getUserSerial());
            }
            mmp.put("member", member == null ? new Member() : member);
            mmp.put("cMemberInfo", cMemberInfo == null ? new CMemberInfo() : cMemberInfo);
            mmp.put("arParent", arParent);
            return AjaxResult.success(mmp);
        } catch (Exception e) {
            logger.error("获取用户信息异常", e);
            return AjaxResult.error("获取用户信息异常", e.getMessage());
        }
    }

    /**
     * @Description: 手机号验证
     * @Param: [ mobile,  memberId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @ResponseBody
    @RequestMapping(value = "checkPartnerUserMobile")
    public AjaxResult checkPartnerUserMobile(String mobile, String memberId) {
        if (StringUtils.isEmpty(mobile)) {
            return AjaxResult.error("参数为空");
        }
        try {
            //可以保存返回true,反之false
            String partnerId = RealmUtils.getCurrentUser().getId();
            boolean b = partnerMemberToBizService.checkPartnerUser(partnerId, memberId, mobile);
            return AjaxResult.success(b);
        } catch (Exception e) {
            logger.error("获取用户信息异常", e);
            return AjaxResult.error("获取用户信息异常", e.getMessage());
        }
    }

    /**
     * 消息发送视图
     *
     * @return 交互数据
     */
    @RequestMapping(value = "messageView")
    public ModelAndView messageView(String targetId, String id, String behavior, Page page) {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        String memberId = currentUser.getId();
        if (RealmUtils.getNewCurrentUser().isXzgsAdmin()) {
            memberId = currentUser.getPartnerId();
        }
        ModelAndView modelAndView = new ModelAndView("/member/messageView");
        TargetTemplate targetTemplate = new TargetTemplate();
        //获取当前登录用户的所有子账号
        List<String> orgIds = new ArrayList<>();
        if (RealmUtils.getNewCurrentUser().isXzgsAdmin()) {
            orgIds = memberGroupService.queryAdminBranchAndXZGSIds(currentUser.getId(),currentUser.getPartnerId());
        }else{
            orgIds = memberGroupService.getChildWithMy(memberId);
        }
        Long memberCount = memberMgmtService.getMemberCountByOrgIds(orgIds);
        page.setLimit(Integer.parseInt(memberCount.toString()));
        MemberMgmtQuery input = new MemberMgmtQuery();
        input.setOrgIds(orgIds);
        //查询会员
        input.setType(0);
        if (!currentUser.isChild()) {
            //主账号查过滤主机构
            input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
        }

        List<Map<String, Object>> list = memberMgmtService.webList(input, null, page);

        modelAndView.addObject("members", list);

        if (!"add".equals(behavior)) {
            //重新发送，获取推送对象
            targetTemplate = targetTemplateService.get(id);
            String memberIds = targetTemplate.getMemberIds();
            String[] mid = memberIds.split(",");
            List<Map<String, Object>> choseMember = new ArrayList<>();
            for (String md : mid) {
                HashMap<String, Object> map = new HashMap<>();
                Member member = memberService.get(md);
                map.put("memberId", member.getId());
                map.put("nickName", member.getRealname());
                choseMember.add(map);
            }
            modelAndView.addObject("members", choseMember);
        } else {
            targetTemplate.setTargetId("kc" + targetId);
        }
        PackageCount packageCount = packageCountService.getUnique(new PackageCount(memberId, TargetType.PUSH_SMS.getCode()));
        modelAndView.addObject("packageCount", packageCount);
        modelAndView.addObject("behavior", behavior);
        modelAndView.addObject("targetTemplate", targetTemplate);

        return modelAndView;
    }

    /**
     * 保存模板同时消息推送
     *
     * @param targetTemplate 目标模板
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "sendAndSave")
    public AjaxResult send(TargetTemplate targetTemplate) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            boolean isCanFlag = memberMgmtNotifyService.sendAndSave(targetTemplate);
            if (!isCanFlag) {
                return AjaxResult.error("短信剩余数量不足，请先充值");
            }
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            logger.error("消息推送异常", be);
            return ajaxResult;
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("发送异常");
            logger.error("消息推送异常", e);
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 消息推送-定时-活动
     *
     * @param targetTemplate
     * @param sendTimeString: 格式为yyyy-MM-dd HH:mm:ss
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendQuartzForMembermgmt")
    public AjaxResult sendQuartzForMember(TargetTemplate targetTemplate, String sendTimeString, String behavior) {

        try {
            return memberMgmtNotifyService.sendQuartz(targetTemplate, sendTimeString, behavior, Constant.SEND_SHORT_MESSAGE_TYPE_MEMBER);
            //return AjaxResult.error("定时短信推送异常");
        } catch (Exception e) {
            logger.error("定时短信推送异常", e);
            return AjaxResult.error("定时短信推送异常");
        }

    }

    /**
     * 删除短信
     *
     * @param id: 模板id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delQuartzForActivity")
    public AjaxResult delQuartzForActivity(String id) {
        try {
            return memberMgmtNotifyService.delQuartzForActivity(id);
        } catch (Exception e) {
            logger.error("删除定时短信异常", e);
            return AjaxResult.error("定时短信删除异常");
        }
    }


    /**
     * @Description:审核用户
     * @Param: [memberId, state]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/10/29
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_CHECK)
    @ResponseBody
    @RequestMapping(value = "checkMember")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult checkMember(String pmId, Integer state) {
        if (StringUtils.isEmpty(pmId) || null == state) {
            return AjaxResult.error("参数不能为空");
        }
        try {
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            String memberId = partnerMember.getMemberId();
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();
            String partnerId = currentUser.getId();
            if (currentUser.isChild()) {
                partnerId = currentUser.getPartnerId();
            }
            Member member = memberService.get(memberId);
            CMemberInfo byMemberId = memberInfoService.getByMemberId(memberId);
            if (byMemberId == null || member == null) {
                return AjaxResult.error("用户信息不存在");
            }
            if (CMemberInfo.CHECK_STATUS_ADOPT == byMemberId.getCheckStatus()) {
                return AjaxResult.error("用户已审核完成");
            }
            if (CMemberInfo.CHECK_STATUS_ADOPT == state) {
                byMemberId.setCheckStatus(CMemberInfo.CHECK_STATUS_ADOPT);

                //如果存在推荐关系即插入推荐积分
//                PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(partnerId, memberId);
                CMemberRecommend cMemberRecommend = new CMemberRecommend();
                cMemberRecommend.setuId(partnerMember.getId());
                List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
                if (list.size() > 0) {
                    try {
                        CMemberRecommend cMemberRecommend1 = list.get(0);
                        PartnerMember partnerMember1 = partnerMemberService.get(cMemberRecommend1.getParentId());
                        integralBizService.insertSystemCIntegralItem(cMemberRecommend1.getId(), partnerId, partnerMember1, null, IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
                    } catch (Exception e) {
                        logger.error("插入推荐积分异常", e.getMessage());
                    }
                }
                try {
                    integralBizService.insertSystemCIntegralItem(null, partnerId, partnerMember, null, IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
                } catch (Exception e) {
                    logger.error("插入赠送积分异常", e.getMessage());
                }
            }
            if (CMemberInfo.CHECK_STATUS_REJECT == state) {
                byMemberId.setCheckStatus(CMemberInfo.CHECK_STATUS_REJECT);

                //将手机号设为空，让用户重新走注册流程
                member.setMobile("");
                memberService.update(member);

                //清空授权登录
                try {
                    redisTokenManager.delRelationshipByKey(member.getId());
                } catch (Exception e) {
                    logger.info("审核拒绝，清除缓存失败,{}", e);
                }

            }
            memberInfoService.update(byMemberId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("审核异常", e);
            return AjaxResult.error("审核异常");
        }
    }

    /**
     * 分配分社
     */
    @RequestMapping(value = "setTag")
    public ModelAndView getTag(String memberId, String partnerId) {
        if (StringUtils.isEmpty(memberId)) {
            return null;
        }
        ModelAndView mv = new ModelAndView("member/setMemberTag");
        MemberGroup currentUser = RealmUtils.getNewCurrentUser();
        if (Constant.MEMBER_XZGSADMIN.equals(currentUser.getType())) {
            currentUser = memberGroupService.get(currentUser.getPartnerId());
        }
        List<String> orgIds = memberGroupService.getChild(currentUser.getId());
        List<MemberGroup> memberGroupList = new ArrayList<>();
        for (String id : orgIds) {
            MemberGroup memberGroup = memberGroupService.get(id);
            memberGroupList.add(memberGroup);
        }
        //获得主分社id
        PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, partnerId);

        String mainPartenrId = "";
        if (mainOrg != null) {
            mainPartenrId = mainOrg.getPartnerId();
        } else {
            PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerId, memberId);
            byPartnerAndMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
            partnerMemberService.update(byPartnerAndMember);
            mainPartenrId = byPartnerAndMember.getPartnerId();
        }

        //获取次分社ids
        String partnerIds = "";
        List<PartnerMember> memberPartners = new ArrayList<>();
        List<String> ids = memberGroupService.getChildWithMy(currentUser.getId());
        for (String id : ids) {
            PartnerMember ciPartenr = new PartnerMember();
            ciPartenr.setMemberId(memberId);
            ciPartenr.setPartnerId(id);
            ciPartenr.setPartnerType(0);
            List<PartnerMember> list = partnerMemberService.getMemberPartners(ciPartenr);
            if (list.size() > 0) {
                memberPartners.add(list.get(0));
            }
        }
        for (PartnerMember member : memberPartners) {
            partnerIds += member.getPartnerId() + ",";
        }

        mv.addObject("partnerIds", partnerIds);
        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("memberId", memberId);
        mv.addObject("mainPartenrId", mainPartenrId);

        return mv;
    }

    /***
     * 修改会员所属分社
     * @Date 20:30 2019/11/14
     * @param ids 已选次分社
     * @param partnerIds 原有次分社
     * @param memberId 会员ID
     * @param partnerMainIds 已选主分社
     * @param partnerMainId 原来主分社
     * @return
     **/
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_ASSIGN_BRANCH)
    @ResponseBody
    @RequestMapping(value = "changeAccout")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public AjaxResult changeAccout(String ids, String partnerIds, String memberId, String partnerMainIds, String partnerMainId) {

        if (StringUtils.isEmpty(memberId) || StringUtils.isEmpty(partnerMainIds)) {
            return AjaxResult.error("主分社必须选择一个");
        }

        try {
            //相比原来所属机构新增的机构关系
            List<String> addList = new ArrayList<>();
            //相比原来所属机构减少的机构关系
            List<String> deleteList = new ArrayList<>();

            //会员要移动到机构ids
            String[] updateIds = ids.split(",");

            //会员原来所属机构ids
            String[] orginIds = partnerIds.split(",");

            //会员主分社的机构id
            String[] memberPartnerMainIds = partnerMainIds.split(",");
            String memberPartnerMainId = memberPartnerMainIds[0];

            for (String orginId : orginIds) {
                if (StringUtils.isNotEmpty(orginId)) {
                    if (!ArrayUtils.contains(updateIds, orginId)) {
                        deleteList.add(orginId);
                    }
                }
            }

            for (String updateId : updateIds) {
                if (StringUtils.isNotEmpty(updateId)) {
                    if (!ArrayUtils.contains(orginIds, updateId)) {
                        addList.add(updateId);
                    }
                }
            }

            //原来主分社移动到次分社
            boolean addFlag = addList.contains(partnerMainId);
            if (addFlag) {
                addList.remove(partnerMainId);
            }
            //原来次分社移动到主分社
            boolean delFlag = deleteList.contains(memberPartnerMainId);
            if (delFlag) {
                deleteList.remove(memberPartnerMainId);
            }

            boolean result = false;

            //相比于原所属机构，增加的机构id
            String[] addArr = addList.toArray(new String[addList.size()]);
            //相比于原所属机构，减少的机构id
            String[] deleteArr = deleteList.toArray(new String[deleteList.size()]);

            //主分社修改
            if (StringUtils.isNotEmpty(partnerMainId) && !memberPartnerMainId.equals(partnerMainId)
                    && !addFlag && !delFlag) {
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerId(memberPartnerMainId);
                partnerMemberService.update(byPartnerAndMember);

                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }
            if (addFlag && !delFlag) {
                //修改原主分社为次分社
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerType(0);
                partnerMemberService.update(byPartnerAndMember);

                //添加主分社
                PartnerMember partnerMember = new PartnerMember();
                partnerMember.setMemberId(memberId);
                partnerMember.setPartnerId(memberPartnerMainId);
                partnerMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                partnerMemberService.insert(partnerMember);

                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }

            if (!addFlag && delFlag) {

                //修改次分社为主分社
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(memberPartnerMainId, memberId);
                byPartnerAndMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                partnerMemberService.update(byPartnerAndMember);
                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                PartnerMember byPartnerAndMember1 = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerType(Integer.valueOf(0));
                partnerMemberService.update(byPartnerAndMember1);

                //将原来主分社推荐关系移动到新的主分社下,
                memberMgmtService.changBindPmIdToMainOrg(byPartnerAndMember1);
                //删除原来主分社机构关系
                partnerMemberService.delete(byPartnerAndMember1.getId());

                result = true;
            }

            if (addFlag && delFlag) {
                //主分社和次分社互换
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerType(0);
                partnerMemberService.update(byPartnerAndMember);

                PartnerMember byPartnerAndMember1 = partnerMemberService.findByPartnerAndMember(memberPartnerMainId, memberId);
                byPartnerAndMember1.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                partnerMemberService.update(byPartnerAndMember1);

                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }

            if (addArr.length == 0 && deleteArr.length == 0 && memberPartnerMainId.equals(partnerMainId)) {
                return AjaxResult.error("没有更改，不用分配");
            } else if (addArr.length == deleteArr.length) {
                //添加和减少的机构相等，不用删除，直接修改partnerId
                for (int i = 0; i < addArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    byPartnerAndMember.setPartnerId(addArr[i]);
                    byPartnerAndMember.setPartnerType(0);
                    partnerMemberService.update(byPartnerAndMember);
                }
                result = true;
            } else if (addArr.length == 0 && deleteArr.length > 0) {
                //只有减少，没有增加，直接删除
                for (String partenrId : deleteArr) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partenrId, memberId);

                    //将推荐关系移动到主分社下
                    memberMgmtService.changBindPmIdToMainOrg(byPartnerAndMember);

                    partnerMemberService.delete(byPartnerAndMember.getId());
                }
                result = true;
            } else if (addArr.length > 0 && deleteArr.length == 0) {
                //只有增加，没有减少，直接添加
                for (String partenrId : addArr) {
                    PartnerMember partnerMember = new PartnerMember();
                    partnerMember.setMemberId(memberId);
                    partnerMember.setPartnerId(partenrId);
                    partnerMember.setPartnerType(0);
                    partnerMemberService.insert(partnerMember);
                }
                result = true;
            } else if (addArr.length > deleteArr.length) {
                //增加的多于删除的，部分更改partnerId，部分新增
                for (int i = 0; i < deleteArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    byPartnerAndMember.setPartnerId(addArr[i]);
                    //不是主分社
                    byPartnerAndMember.setPartnerType(0);
                    partnerMemberService.update(byPartnerAndMember);
                }
                for (int i = deleteArr.length; i < addArr.length; i++) {
                    PartnerMember partnerMember = new PartnerMember();
                    partnerMember.setMemberId(memberId);
                    partnerMember.setPartnerId(addArr[i]);
                    partnerMember.setPartnerType(0);
                    partnerMemberService.insert(partnerMember);
                }
                result = true;
            } else if (addArr.length < deleteArr.length) {
                //删除的多余增加的，更改部分partnerId,其余的直接删除
                for (int i = 0; i < addArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    byPartnerAndMember.setPartnerId(addArr[i]);
                    byPartnerAndMember.setPartnerType(0);
                    partnerMemberService.update(byPartnerAndMember);
                }

                for (int i = addArr.length; i < deleteArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    //将推荐关系移动到主分社下
                    memberMgmtService.changBindPmIdToMainOrg(byPartnerAndMember);

                    partnerMemberService.delete(byPartnerAndMember.getId());
                }

                result = true;
            }
            if (result) {
                redisTokenManager.delRelationshipByKey(memberId);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("更改会员所属机构失败");
            }

        } catch (Exception e) {
            logger.error("更改会员所属机构失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更改机构关系失败");
        }
    }

    /**
     * @Description:绑定推荐关系视图
     * @Param: [memberId]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/11/20
     */
    @RequestMapping(value = "bindingRRView")
    public ModelAndView bindingRRView(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return null;
        }
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        //推荐类型的积分项
        List<CIntegralItem> cIntegralItems = null;
        //推荐人
        Member tjMember = null;
        //积分
        CUserIntegral cUserIntegral = null;
        //积分项
        CIntegralItem cIntegralItem = null;
        try {
            //主机构
            PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, currentUser.getId());
            //推荐的人
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setuId(mainOrg.getId());
            List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
            if (list.size() > 0) {
                CMemberRecommend crOrg = list.get(0);

                //获取推荐的人
                PartnerMember partnerMember = partnerMemberService.get(crOrg.getParentId());
                tjMember = memberService.get(partnerMember.getMemberId());

                //获取推荐的人对应加的积分
                CUserIntegral cuiOrg = new CUserIntegral();
                cuiOrg.setRecommendId(crOrg.getId());
                List<CUserIntegral> list1 = userIntegralService.list(cuiOrg);
                cUserIntegral = list1.get(0);
                //对应的积分项
                cIntegralItem = cIntegralItemService.get(cUserIntegral.getIntegralItemId());
            }

            //积分项列表
            String partnerId = memberGroupService.getPartnerId(currentUser.getId());
            CIntegralType cIntegralType = new CIntegralType();
            cIntegralType.setCategory(IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
            cIntegralType.setCreateBy(partnerId);
            List<CIntegralType> cIntegralTypes = integralTypeService.list(cIntegralType);
            if (cIntegralTypes.size() > 0) {
                cIntegralType = cIntegralTypes.get(0);
            } else {
                throw new BusinessException("没有找到推荐类型的积分类型");
            }
            CIntegralItem ciiOrg = new CIntegralItem();
            ciiOrg.setCreateBy(partnerId);
            ciiOrg.setTypeId(cIntegralType.getId());
            cIntegralItems = cIntegralItemService.list(ciiOrg);

        } catch (Exception e) {
            logger.error("查看推荐关系异常", e.getMessage());
            return null;
        }
        ModelAndView mv = new ModelAndView("member/bindingRRView");
        mv.addObject("memberId", memberId);
        mv.addObject("tjMember", tjMember);
        mv.addObject("cUserIntegral", cUserIntegral);
        mv.addObject("cIntegralItem", cIntegralItem);
        mv.addObject("cIntegralItems", cIntegralItems);
        return mv;
    }

    /**
     * @Description:绑定推荐关系
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_RECOMMEND_INSERT)
    @ResponseBody
    @RequestMapping(value = "/bindingRR", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult bindingRR(String cuserId, String memberId, String tjMemberId, String integralItemId, String tjMemberMobile) {

        if (StringUtils.isEmpty(memberId) ||
                (StringUtils.isEmpty(tjMemberMobile) && StringUtils.isEmpty(tjMemberId)) ||
                StringUtils.isEmpty(integralItemId)) {
            return AjaxResult.error("参数为空");
        }

        try {
            if (StringUtils.isNotEmpty(cuserId)) {
                /*                  修改推荐积分*/
                CUserIntegral cUserIntegral = userIntegralService.get(cuserId);
                if (!integralItemId.equals(cUserIntegral.getIntegralItemId())) {
                    cUserIntegral.setIntegralItemId(integralItemId);
                    userIntegralService.update(cUserIntegral);
                }
            } else {
                /*                  绑定推荐关系*/

                MemberGroup currentUser = RealmUtils.getCurrentUser();
                //当前登录机构id
                String orgId = currentUser.getId();
                //主机构id
                String partnerId = orgId;
                if (StringUtils.isNotEmpty(currentUser.getPartnerId())) {
                    partnerId = currentUser.getPartnerId();
                }

                CIntegralItem cIntegralItem = cIntegralItemService.get(integralItemId);
                if (null == cIntegralItem) {
                    return AjaxResult.error("积分项不存在");
                }
                if (memberId.equals(tjMemberId)) {
                    return AjaxResult.error("推荐人不能是当前用户");
                }
                if (StringUtils.isEmpty(tjMemberId)) {
                    List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
                    List<Map<String, Object>> list = memberService.findPartnerMemberByPhoneOrName2("phone", tjMemberMobile, Member.MEMBER_PERSONAL, orgIds);
                    if (list.size() == 0) {
                        return AjaxResult.error("推荐人不存在");
                    } else {
                        Map<String, Object> mmp = list.get(0);
                        tjMemberId = mmp.get("id").toString();
                    }
                }


                /*   判断是否存在 相互推荐*/
                //主分社
                PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, orgId);
                //推荐人主分社
                PartnerMember tj_mainOrg = partnerMemberService.getMainOrg(tjMemberId, orgId);

                /* 推荐关系绑定*/
                CMemberRecommend newMemberRecommend = new CMemberRecommend();
                newMemberRecommend.setuId(mainOrg.getId());
                newMemberRecommend.setParentId(tj_mainOrg.getId());
                List<CMemberRecommend> list = memberRecommendService.list(newMemberRecommend);
                if (list.size() == 0) {
                    CMemberRecommend cMemberRecommend = new CMemberRecommend();
                    cMemberRecommend.setParentId(mainOrg.getId());
                    cMemberRecommend.setuId(tj_mainOrg.getId());
                    List<CMemberRecommend> t_list = memberRecommendService.list(cMemberRecommend);
                    if (t_list.size() > 0) {
                        return AjaxResult.error("不能相互推荐");
                    }
                    //插入推荐关系
                    memberRecommendService.insert(newMemberRecommend);
                }
                //插入推荐积分
                integralBizService.insertSystemCIntegralItem(newMemberRecommend.getId(), partnerId, tj_mainOrg, cIntegralItem.getId(), IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑积分异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑积分异常");
        }
    }


    /**
     * @Description:添加赠送积分
     * @Param:AjaxResult
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/addGiftIntegral")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult addGiftIntegral() {
        CurrentUser member = RealmUtils.getNewCurrentUser();
        MemberMgmtQuery input = new MemberMgmtQuery();

        //获取所有主分社用户
        List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
        input.setOrgIds(orgIds);
        input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
        List<Map<String, Object>> list = memberMgmtService.webList(input, "", null);
        ArrayList<String> noChecklist = Lists.newArrayList();

        int sucNum = 0;
        int errNum = 0;
        int noCheckNum = 0;
        for (Map<String, Object> mmp : list) {
            //添加赠送积分
            String memberId = mmp.get("memberId").toString();
            String partnerId = mmp.get("partnerId").toString();
            Integer checkStatus = Integer.parseInt(mmp.get("checkStatus").toString());
            Date createDate = new Date();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                createDate = sdf.parse(mmp.get("createTime").toString());
            } catch (Exception e) {
                logger.error("添加赠送积分失败，字符串转日期异常：" + mmp.get("createTime").toString());
            }

            PartnerMember partnerMember = new PartnerMember();
            partnerMember.setMemberId(memberId);
            partnerMember.setPartnerId(partnerId);
            partnerMember.setCreateDate(createDate);
            try {
                if (checkStatus == CMemberInfo.CHECK_STATUS_ADOPT) {
                    integralBizService.insertSystemCIntegralItem(null, member.getId(), partnerMember, null, IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
                    sucNum++;
                } else {
                    noCheckNum++;
                    noChecklist.add(member.getId());
                }
            } catch (Exception e) {
                errNum++;
                logger.error("添加赠送积分失败:" + JSONObject.toJSONString(mmp), e.getMessage());
            }
        }
        return AjaxResult.success("一共有" + list.size() + "个会员，" + sucNum + "个添加成功；" + errNum + "个添加失败，其中" + noCheckNum + "个是未审核通过的用户 noChecklist:" + JSONObject.toJSONString(noChecklist));
    }

    /**
     * 获取用户
     *
     * @param input
     * @param page
     * @returns
     */
    @RequestMapping(value = "/selectNewMember")
    public ModelAndView selectNewMember(SelectMemberInput input, Page page) {
        if (StringUtils.isEmpty(input.getPartnerId())) {
            logger.error("动态_获取用户失败");
            return null;
        }

        MemberGroup memberGroup = memberGroupService.get(input.getPartnerId());
        List<String> orgIds = memberGroupService.getChildWithMy(memberGroup.getId());
        MemberMgmtQuery queryinput = new MemberMgmtQuery();
        if (StringUtils.isNotEmpty(input.getMobile())) {
            queryinput.setMobile(input.getMobile());
        }
        if (StringUtils.isNotEmpty(input.getRealname())) {
            queryinput.setNickName(input.getRealname());
        }
        page.setLimit(10);
        queryinput.setOrgIds(orgIds);
        queryinput.setType(0);
        if (StringUtils.isEmpty(memberGroup.getPartnerId())) {
            queryinput.setPartnerType(PartnerMember.IS_MAIN_TYPE);
        }
        queryinput.setCheckStatus(CMemberInfo.CHECK_STATUS_ADOPT);

        List<Map<String, Object>> memberList = memberMgmtService.webList(queryinput, "", page);

        ModelAndView mv = new ModelAndView("/member/selectNewMember");
        mv.addObject("page", page);
        mv.addObject("memberInput", input);
        mv.addObject("memberList", memberList);
        return mv;
    }
}
